<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    #div1 {
      width: 100px;
      height: 200px;
      background-color: gray;
      position: absolute;
      left: -100px;
      top: 400px;
    }

    span {
      width: 20px;
      height: 60px;
      background-color: hotpink;
      position: absolute;
      left: 100px;
      top: 70px;
    }

    img {
      opacity: 0.3;
      filter: alpha(opacity=30);
      /* 浏览器兼容 */
    }
  </style>
  <script>
    window.onload = function () {
      var oDiv = document.getElementById("div1");
      var oImg = document.getElementsByTagName("img")[0];
      oDiv.onmouseover = function () {
        startMove(0);
      };
      oDiv.onmouseout = function () {
        startMove(-100);
      };
      oImg.onmouseover = function () {
        startMove2(100);
      };
      oImg.onmouseout = function () {
        startMove2(30);
      };
      var timer2 = null;
      var alpha = 30;

      function startMove2(oTarget) {
        var speed = 2;
        clearTimeout(timer2);
        if (oTarget > alpha) {
          speed = Math.abs(speed);
        } else {
          speed = -Math.abs(speed);
        }
        timer2 = setInterval(function () {
          alpha += speed;
          if (alpha === oTarget) {
            clearTimeout(timer2);
          }
          oImg.style.opacity = alpha / 100;
          oImg.style.filter = `alpha(opacity=${alpha})`;
        }, 30);
      }
      var timer = null;

      function startMove(oTarget) {
        var speed = 5;
        clearInterval(timer);
        if (oTarget > oDiv.offsetLeft) {
          speed = Math.abs(speed);
        } else {
          speed = -Math.abs(speed);
        }
        timer = setInterval(function () {
          oDiv.style.left = oDiv.offsetLeft + speed + "px";
          if (oDiv.offsetLeft === oTarget) {
            clearInterval(timer);
          }
        }, 30);
      }
      // function startMove2() {
      //   clearInterval(timer);
      //   var speed = -5;
      //   timer = setInterval(function () {
      //     oDiv.style.left = oDiv.offsetLeft + speed + "px";
      //     if (oDiv.offsetLeft === -100) {
      //       clearInterval(timer);
      //     }
      //   }, 30);
      // }
    };
  </script>
</head>

<body>
  <div id="div1"><span>分享到</span></div>
  <img src="img/img1.jpg" alt="" />
</body>

</html>